package cn.xyy.web;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.xyy.common.domain.mvc.R;
import cn.xyy.common.exception.SystemException;
import cn.xyy.common.utils.LoggerUtil;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * 
 * @author xyy
 *
 */
@RestControllerAdvice
class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleGlobalException(Exception e) {
		LoggerUtil.error("全局异常信息 ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

	@ExceptionHandler(SystemException.class)
	public R handleGlobalException(SystemException e) {
		LoggerUtil.error("SystemException ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

	@ExceptionHandler(NotLoginException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R handleNotLoginException(NotLoginException e) {
		LoggerUtil.warn("用户未登录 ex={}", e.getMessage(), e);

		// 判断场景值，定制化异常信息
		String message = "";
		if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
			message = "未提供token";
		} else if (e.getType().equals(NotLoginException.INVALID_TOKEN)) {
			message = "token无效";
		} else if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
			message = "token已过期";
		} else if (e.getType().equals(NotLoginException.BE_REPLACED)) {
			message = "token已被顶下线";
		} else if (e.getType().equals(NotLoginException.KICK_OUT)) {
			message = "token已被踢下线";
		} else {
			message = "当前会话未登录";
		}

		return R.error(401, message);
	}

	@ExceptionHandler(NotPermissionException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleNotPermissionException(NotPermissionException e) {
		LoggerUtil.warn("用户没有权限 ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

}